package tech.mhuang.pacebox.core.strategy;

import tech.mhuang.pacebox.core.exception.BusinessException;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认实现策略模式
 *
 * @author mhuang
 * @since 1.0.12
 */
public abstract class AbstractStrategyManager<REQUEST, RESPONSE> implements BaseStrategyManager<REQUEST, RESPONSE> {

    private volatile Map<String, BaseStrategyServer<REQUEST, RESPONSE>> serverMap = new ConcurrentHashMap<>();

    /**
     * 初始化调用
     */
    public abstract void init();

    @Override
    public void set(String event, BaseStrategyServer<REQUEST, RESPONSE> strategyServer) {
        serverMap.put(event, strategyServer);
    }

    @Override
    public BaseStrategyServer<REQUEST, RESPONSE> get(String event) {
        return serverMap.get(event);
    }

    @Override
    public Map<String, BaseStrategyServer<REQUEST, RESPONSE>> serverMap() {
        return serverMap;
    }

    @Override
    public void refresh(Map<String, BaseStrategyServer<REQUEST, RESPONSE>> serverMap) {
        this.serverMap.clear();
        this.serverMap.putAll(serverMap);
    }

    /**
     * 默认策略调用方式
     *
     * @param param 事件
     * @return 策略执行结果
     */
    @Override
    public StrategyHandlerResult<RESPONSE> strategy(StrategyHandlerParam<REQUEST> param) {
        BaseStrategyServer<REQUEST, RESPONSE> strategyManager = serverMap.get(param.getEvent());
        if (Optional.of(strategyManager).isPresent()) {
            return strategyManager.strategy(param);
        }
        throw new BusinessException(500, "invalid strategyManager key:" + param.getEvent());
    }
}
